<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片式 -->
    <el-card>
      <!-- 添加分类按钮 -->
      <el-row>
        <el-col>
          <el-button type="primary" @click="addDialogVisible = true">添加分类</el-button>
        </el-col>
      </el-row>
  
      <!-- tree-table插件 -->
      <tree-table :data="goodsTable" :columns="columns" show-index index-text="#" :show-row-hover="false"
      border :selection-type="false" :expand-type="false" style="margin: 15px 0;" max-height="500px" :autoRowHeight="false">
        <!-- 是否有效插槽 -->
        <template slot="isok" slot-scope="scope">
          <i class="el-icon-success" style="color: lightgreen" v-if="scope.row.cat_deleted === false"></i>
          <i class="el-icon-error" style="color: red" v-else></i>
        </template>

        <!-- 排序插槽 -->
        <template slot="level" slot-scope="scope">
          <el-tag v-if="scope.row.cat_level === 0">一级</el-tag>
          <el-tag v-else-if="scope.row.cat_level === 1" type="success">二级</el-tag>
          <el-tag v-else type="warning">三级</el-tag>
        </template>

        <!-- 操作插槽 -->
        <template slot="operation" slot-scope="scope">
          <el-button type="primary" icon="el-icon-edit" size="mini" @click="editDialogShow(scope.row)">编辑</el-button>
          <el-button type="danger" icon="el-icon-delete" size="mini" @click="delDialogShow(scope.row)">删除</el-button>
        </template>
      </tree-table>
      <div class="block">
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" 
        :current-page="pagenum" :page-sizes="[1, 2, 5, 10]" :page-size="pagesize" 
        layout="total, sizes, prev, pager, next, jumper" :total="total">
        </el-pagination>
      </div>
    </el-card>

    <!-- 添加分类对话框 -->
    <el-dialog title="添加分类" :visible.sync="addDialogVisible" width="50%" :before-close="addDialogClose">
      <!-- body -->
      <el-form :model="addForm" :rules="addRules" ref="addFormRef" label-width="100px" class="demo-ruleForm">
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="addForm.cat_name"></el-input>
        </el-form-item>
        <el-form-item label="父级分类">
          <div class="block">
            <el-cascader expand-trigger="hover" :options="allGoodsTable" :props="cascaderProps" 
            v-model="selectedKeys" @change="parentCateChange" clearable change-on-select>
            </el-cascader>
          </div>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogClose">取 消</el-button>
        <el-button type="primary" @click="addSend">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑分类对话框 -->
    <el-dialog title="编辑分类" :visible.sync="editDialogVisible" width="50%" :before-close="editDialogClose">
      <!-- body -->
      <el-form :model="editForm" :rules="editRules" ref="editFormRef" label-width="100px" class="demo-ruleForm">
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="editForm.cat_name"></el-input>
        </el-form-item>
        <!-- <el-form-item label="父级分类">
          <div class="block">
            <el-cascader expand-trigger="hover" :options="allGoodsTable" :props="cascaderProps" 
            v-model="selectedKeys2" @change="parentCateChange2" clearable change-on-select>
            </el-cascader>
          </div>
        </el-form-item> -->
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogClose">取 消</el-button>
        <el-button type="primary" @click="editSend">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      goodsTable: [],
      allGoodsTable: [],
      firstLevelCate: [],
      secondLevelCata: [],
      thildLevelCate: [],
      editDialogVisible: false,
      editForm: {
        cat_name: '',
        cat_pid: 0,
        cat_level: 0,
      },
      editRules: {
        cat_name: [
          { required: true, message: '请输入分类名称', trigger: 'blur' },
          { min: 1, max: 15, message: '长度在 1 到 15 个字符', trigger: 'blur' }
        ],
      },
      total: 0,
      // 当前的页数
      pagenum: 1,
      // 当前每页显示多少条数据
      pagesize: 5,
      addDialogVisible: false,
      // 为table指定列的定义
      addForm: {
        cat_name: '',
        cat_pid: 0,
        // 默认是一级分类
        cat_level: 0,
      },
      addRules: {
        cat_name: [
          { required: true, message: '请输入分类名称', trigger: 'blur' },
          { min: 1, max: 15, message: '长度在 1 到 15 个字符', trigger: 'blur' }
        ],
      },
      // 指定级联选择器的配置对象
      cascaderProps: {
        value: 'cat_id',
        label: 'cat_name',
        childer: 'children',
      },
      // 选中的父级分类的id数组
      selectedKeys: [],
      // 编辑对话框de 
      // selectedKeys2: [],
      thisCatId: '',
      columns: [{
        label: '分类名称',
        prop: 'cat_name',
        width: '180px'
      }, {
        prop: "cat_deleted",
        label: "是否有效",
        width: '180px',
        // 将当前列定义为模板列
        type: 'template',
        // 指定使用哪个模板,
        template: 'isok'
      }, {
        prop: "cat_level",
        label: "排序",
        width: '180px',
        type: 'template',
        template: 'level'
      }, {
        label: "操作",
        width: '180px',
        type: 'template',
        template: 'operation'
      }],
    }
  },
  created() {
    this.getGoodsCate()
  },
  methods: {
    parentCateChange() {
      console.log(this.selectedKeys)
      if(this.selectedKeys.length > 0) {
        // 选中了父级分类
        this.addForm.cat_pid = this.selectedKeys[this.selectedKeys.length - 1]
        this.addForm.cat_level = this.selectedKeys.length
        return
      }else {
        // 没有选中任何父级分类
        this.addForm.cat_pid = 0
        this.addForm.cat_level = 0
      }
    },
    // parentCateChange2() {
      
    // },
    handleSizeChange(newSize) {
      this.pagesize = newSize
      console.log(this.pagesize)
      this.goodsTable = []
      this.getGoodsCate()
    },
    handleCurrentChange(newCurrent) {
      this.pagenum = newCurrent
      console.log(this.pagenum)
      this.goodsTable = []
      this.getGoodsCate()
    },
    getGoodsCate() {
      this.$http.get('categories', {
        type: '',
        pagenum: '',
        pagesize: ''
      }).then(res => {
        console.log(res.data.data)
        this.goodsTable = []
        var allReqArr = res.data.data
        this.allGoodsTable = res.data.data
        var total = allReqArr.length
        this.total = total
        var index = (this.pagenum - 1) * this.pagesize
        var pageMax = this.pagenum * this.pagesize
        if(pageMax > this.total){
          for (var i = index; i < this.total; i++) {
            this.goodsTable.push(allReqArr[i])
          }
        }else {
          for (var i = index; i < pageMax; i++) {
            this.goodsTable.push(allReqArr[i])
          }
        } 
      })
    },
    addDialogClose() {
      this.$refs.addFormRef.resetFields()
      this.addDialogVisible = false
    },
    addSend() {
      this.$refs.addFormRef.validate((valid) => {
        if (valid) {
          this.$http.post('categories', {
            cat_pid: this.addForm.cat_pid,
            cat_name: this.addForm.cat_name,
            cat_level: this.addForm.cat_level
          }).then(res => {
            if(res.data.meta.status !== 201) {
              this.$message.error(res.data.meta.msg)
            }else{
              this.getGoodsCate()
              this.addDialogVisible = false
              this.$message.success("添加成功")
            }
          })
        } else {
          this.$message.error("添加失败")
          return false;
        }
      });
    },
    editDialogShow(scopeRow) {
      this.editDialogVisible = true
      this.editForm.cat_name = scopeRow.cat_name
      this.editForm.cat_pid = scopeRow.cat_pid
      this.editForm.cat_level = scopeRow.cat_level
      this.thisCatId = scopeRow.cat_id
    },
    delDialogShow(scopeRow) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).then(() => {
        // 确认删除 , 执行
        this.$http.delete(`categories/${scopeRow.cat_id}`).then(res => {
          if(res.data.meta.status !== 200) {
            this.$message.error(res.data.meta.msg)
          }else{
            this.getGoodsCate()
            this.$message.success("删除成功")
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    editDialogClose() {
      this.$refs.editFormRef.resetFields()
      this.editDialogVisible = false
    },
    editSend() {
      this.$refs.editFormRef.validate((valid) => {
        if (valid) {
          this.$http.put(`categories/${this.thisCatId}`, {
            cat_name: this.editForm.cat_name,
          }).then(res => {
            if(res.data.meta.status !== 200) {
              this.$message.error(res.data.meta.msg)
            }else{
              this.getGoodsCate()
              this.editDialogVisible = false
              this.$message.success("修改成功")
            }
          })
        } else {
          this.$message.error("修改失败")
          return false;
        }
      });
    }
  },
}
</script>
<style lang="scss" scoped>
  
</style>